package com.hserver.statistics.action.api;

import com.hserver.statistics.bean.Menu;
import top.hserver.core.interfaces.HttpRequest;
import top.hserver.core.interfaces.HttpResponse;
import top.hserver.core.ioc.annotation.Controller;
import top.hserver.core.ioc.annotation.GET;
import com.hserver.statistics.util.MenuUtil;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Controller
public class IndexAction {

    @GET("/")
    public void renderIndex(HttpResponse response) {
        List<Menu> menus = MenuUtil.generateMenu();
        HashMap<String,Object> menusa=new HashMap<>();
        menusa.put("menus",menus);
        response.sendTemplate("index.ftl",menusa);
    }

    @GET("/show")
    public void show(HttpResponse response, HttpRequest request) {
        String baseUrl = request.query("url").trim();
        String url = baseUrl.substring(0, baseUrl.lastIndexOf(File.separator));
        File file = new File(url);
        List<String> times = new ArrayList<>();
        String baseName = baseUrl.substring(baseUrl.lastIndexOf(File.separator) + 1, baseUrl.length());
        System.out.println(baseName);
        if (file.isDirectory()) {
            String[] list = file.list();
            //取时间.
            for (String s : list) {

                String fileName = s.substring(0, s.lastIndexOf("."));
                String name = fileName.substring(0, fileName.length() - 8);
                int i = name.lastIndexOf("-");
                String vx = name.substring(0, i);
                String time = fileName.substring(vx.length() + 1);
                if (!times.contains(time)) {
                    times.add(time);
                }
            }
        }
        List<Menu> menus = MenuUtil.generateMenu();
        HashMap<String,Object> data=new HashMap<>();
        data.put("menus", menus);
        data.put("baseName", baseName);
        try {
            data.put("basePath", URLDecoder.decode(url, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        data.put("times", times);
        response.sendTemplate("show.ftl",data);
    }
}
